package com.alibaba.dubbo.demo.consumer;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.rpc.*;

public class TPMonitorFilter implements Filter {

    private TPMonitor tpMonitor;

    public TPMonitorFilter() {
        this.tpMonitor = new TPMonitor();
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long start = System.currentTimeMillis();
        Result result = invoker.invoke(invocation);

        // 记录方法请求耗时（异步调用不进行记录）
        if (!Boolean.TRUE.toString().equals(invocation.getAttachment(Constants.ASYNC_KEY))) {
            int elapsedMs = (int) (System.currentTimeMillis() - start);
            tpMonitor.recordMethodInvokeTime(start, invocation.getMethodName(), elapsedMs);
        }

        return result;
    }

}
